import type { RouteRecordRaw } from "vue-router";
import { createRouter, createWebHashHistory } from "vue-router";
import defaultRoutes from "./defaultRoutes";
import { post } from "@/common/http";
import { useSysStore } from "@/store/sys";
import { routerTypeName } from "@/common/interface";

const router = createRouter({
  history: createWebHashHistory(),
  routes: [...defaultRoutes] as RouteRecordRaw[],
});

// router.addRoute({ name: 'admin', path: '/admin', component: Admin })
// router.addRoute('admin', { path: 'settings', component: AdminSettings })

// // 这等效于：
// router.addRoute({
//   name: 'admin',
//   path: '/admin',
//   component: Admin,
//   children: [{ path: 'settings', component: AdminSettings }],
// })

let routerMark = false;
router.beforeEach(async (to, from, next) => {
  const { activeRoutes, bottonPower } = toRefs(useSysStore());
  let token = localStorage.getItem("token");
  if (to.path === "/login") {
    routerMark = false;
    bottonPower.value = [];
    activeRoutes.value.forEach((v) => {
      // 过滤判断菜单类型不包含页面按钮
      if (v.type != routerTypeName.button) {
        router.removeRoute(v.name);
      }
    });
    router.removeRoute("404");
    next();
  } else {
    if (token) {
      //判断是否已经动态添加过路由
      if (routerMark) {
        next();
      } else {
        let modules = import.meta.glob("@/views/**/*.vue"); //载入所有页面
        let node = await post("api/Admin/getRoleNode"); //获取登录角色的路由

        activeRoutes.value = node.data;
        //获取页面按钮
        node.data.forEach((v: any) => {
          if (v.type === routerTypeName.button) {
            bottonPower.value.push(v.url as never);
          }
        });
        node.data.forEach((v: any) => {
          // 过滤判断菜单类型不包含页面按钮
          if (v.type != routerTypeName.button) {
            router.addRoute({
              path: v.url,
              name: v.name,
              component: modules[`/src/views/${v.component}.vue`],
            });
          }
        });
        //动态添加404页面，否则会导致登录后直接进入404页面
        router.addRoute({
          path: "/:pathMatch(.*)*",
          name: "404",
          component: () => import("@/views/sys/notFound.vue"),
        });
        next({ ...to, replace: true });
        routerMark = true;
      }
    } else {
      next({
        path: "/login",
      });
    }
  }
});
export default router;
